<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Shop } from '@element-plus/icons-vue'
import { 
  getMerchantInfoService,
  updateMerchantService,
  updateMerchantLogoService,
  updateMerchantPwdService
} from '../../api/merchant'
import { uploadAvatarService } from '../../api/user'
import { useMerchantStore } from '../../stores/merchant'

const router = useRouter()
const merchantStore = useMerchantStore()

// 商家基本信息表单
const infoForm = reactive({
  name: '',
  description: '',
  province: '',
  city: '',
  district: '',
  detail: ''
})

// 密码修改表单
const pwdForm = reactive({
  newPwd: '',
  rePwd: ''
})

const infoFormRef = ref()
const pwdFormRef = ref()

// 表单验证规则
const infoRules = {
  name: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' },
    { min: 1, max: 16, message: '店铺名称长度为1-16个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入店铺描述', trigger: 'blur' }
  ],
  province: [
    { required: true, message: '请输入省份', trigger: 'blur' }
  ],
  city: [
    { required: true, message: '请输入城市', trigger: 'blur' }
  ],
  district: [
    { required: true, message: '请输入区/县', trigger: 'blur' }
  ],
  detail: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ]
}

const pwdRules = {
  newPwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 5, max: 16, message: '密码长度为5-16个字符', trigger: 'blur' }
  ],
  rePwd: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (_rule: any, value: any, callback: any) => {
        if (value !== pwdForm.newPwd) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 加载商家信息
const loadMerchantInfo = async () => {
  try {
    const res: any = await getMerchantInfoService()
    if (res.code === 0) {
      const data = res.data
      merchantStore.setMerchantInfo(data)
      infoForm.name = data.name
      infoForm.description = data.description
      infoForm.province = data.province
      infoForm.city = data.city
      infoForm.district = data.district
      infoForm.detail = data.detail
    }
  } catch (error) {
    console.error('加载商家信息失败:', error)
    ElMessage.error('加载商家信息失败')
  }
}

// 上传Logo
const handleLogoUpload = async (file: any) => {
  try {
    const res: any = await uploadAvatarService(file.raw)
    if (res.code === 0) {
      const logoUrl = res.data
      await updateMerchantLogoService(logoUrl)
      merchantStore.updateMerchantLogo(logoUrl)
      ElMessage.success('Logo更新成功')
    }
  } catch (error) {
    console.error('Logo上传失败:', error)
    ElMessage.error('Logo上传失败')
  }
}

// 更新基本信息
const handleUpdateInfo = async () => {
  try {
    await infoFormRef.value.validate()
    await updateMerchantService(infoForm)
    merchantStore.updateMerchantInfo(infoForm)
    ElMessage.success('信息更新成功')
  } catch (error: any) {
    if (error !== false) {
      console.error('更新失败:', error)
      ElMessage.error('更新失败')
    }
  }
}

// 修改密码
const handleUpdatePwd = async () => {
  try {
    await pwdFormRef.value.validate()
    await updateMerchantPwdService(pwdForm.newPwd, pwdForm.rePwd)
    ElMessage.success('密码修改成功，请重新登录')
    merchantStore.clearMerchant()
    router.push('/merchant/auth')
  } catch (error: any) {
    if (error !== false) {
      console.error('密码修改失败:', error)
      ElMessage.error('密码修改失败')
    }
  }
}

onMounted(() => {
  // 检查商家是否已登录
  if (!merchantStore.isLoggedIn || !merchantStore.merchantToken) {
    ElMessage.warning('请先登录商家账号')
    router.push('/merchant/auth')
    return
  }
  
  loadMerchantInfo()
})
</script>

<template>
  <div class="merchant-profile">
    <!-- 头部 -->
    <div class="page-header">
      <h2>商家信息</h2>
      <div class="header-actions">
        <el-button @click="router.push('/merchant/dashboard')">返回商品管理</el-button>
      </div>
    </div>

    <div class="content">
      <!-- Logo上传 -->
      <el-card class="logo-card">
        <template #header>
          <div class="card-header">
            <span>店铺Logo</span>
          </div>
        </template>
        <div class="logo-upload">
          <el-avatar :size="120" :src="merchantStore.merchantLogo">
            <el-icon :size="60"><Shop /></el-icon>
          </el-avatar>
          <el-upload
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleLogoUpload"
            accept="image/*"
          >
            <el-button type="primary" style="margin-top: 1rem">更换Logo</el-button>
          </el-upload>
        </div>
      </el-card>

      <!-- 基本信息 -->
      <el-card class="info-card">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        <el-form
          ref="infoFormRef"
          :model="infoForm"
          :rules="infoRules"
          label-width="100px"
        >
          <el-form-item label="商户余额">
            <el-input :value="`¥${merchantStore.balance?.toFixed(2) || '0.00'}`" disabled />
          </el-form-item>
          <el-form-item label="店铺名称" prop="name">
            <el-input v-model="infoForm.name" />
          </el-form-item>
          <el-form-item label="店铺描述" prop="description">
            <el-input
              v-model="infoForm.description"
              type="textarea"
              :rows="3"
            />
          </el-form-item>
          <el-form-item label="省份" prop="province">
            <el-input v-model="infoForm.province" />
          </el-form-item>
          <el-form-item label="城市" prop="city">
            <el-input v-model="infoForm.city" />
          </el-form-item>
          <el-form-item label="区/县" prop="district">
            <el-input v-model="infoForm.district" />
          </el-form-item>
          <el-form-item label="详细地址" prop="detail">
            <el-input v-model="infoForm.detail" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleUpdateInfo">保存修改</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 密码修改 -->
      <el-card class="pwd-card">
        <template #header>
          <div class="card-header">
            <span>修改密码</span>
          </div>
        </template>
        <el-form
          ref="pwdFormRef"
          :model="pwdForm"
          :rules="pwdRules"
          label-width="100px"
        >
          <el-form-item label="新密码" prop="newPwd">
            <el-input
              v-model="pwdForm.newPwd"
              type="password"
              show-password
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="rePwd">
            <el-input
              v-model="pwdForm.rePwd"
              type="password"
              show-password
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleUpdatePwd">修改密码</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<style scoped lang="scss">
.merchant-profile {
  padding: 2rem;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 1.5rem 2rem;
  border-radius: 8px;
  margin-bottom: 1.5rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  h2 {
    margin: 0;
    font-size: 1.5rem;
    color: #333;
  }
}

.content {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 1.5rem;

  @media (max-width: 1024px) {
    grid-template-columns: 1fr;
  }
}

.logo-card {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .logo-upload {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 2rem;
  }
}

.info-card,
.pwd-card {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  font-weight: 600;
  font-size: 1.1rem;
}
</style>
